package com.bitdf.txing.common.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bitdf.txing.common.vo.PageVO;
import com.bitdf.txing.common.xss.SQLFilter;
import org.apache.commons.lang.StringUtils;

/**
 * @author Lizhiwei
 * @date 2023/8/22 11:14:17
 * @description 查询参数
 */
public class Query<T> {

    public IPage<T> getPage(PageVO pageModel) {
        return this.getPage(pageModel, null, false);
    }

    public IPage<T> getPage(PageVO pageModel, String defaultOrderField, boolean isAsc) throws NumberFormatException{
        //分页参数
        long curPage = 1;
        long limit = 10;

        if(pageModel.page != null){
            curPage = Long.parseLong(pageModel.page);
        }
        if(pageModel.limit != null){
            limit = Long.parseLong(pageModel.limit);
        }

        //分页对象
        Page<T> page = new Page<>(curPage, limit);

        //排序字段
        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String orderField = SQLFilter.sqlInject(pageModel.orderField);
        String order = pageModel.order;


        //前端字段排序
        if(StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)){
            if("asc".equalsIgnoreCase(order)) {
                return  page.addOrder(OrderItem.asc(orderField));
            }else {
                return page.addOrder(OrderItem.desc(orderField));
            }
        }

        //没有排序字段，则不排序
        if(StringUtils.isBlank(defaultOrderField)){
            return page;
        }

        //默认排序
        if(isAsc) {
            page.addOrder(OrderItem.asc(defaultOrderField));
        }else {
            page.addOrder(OrderItem.desc(defaultOrderField));
        }

        return page;
    }
}
